﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace PMCSerialTransfer
{
    static public class Globals
    {
        public enum ProgressType
        {
            Load,
            Add,
            Clear,
            None
        }

        public enum ACKType
        {
            E_ACK = 0,
            E_NACK = 1,
            E_ERR = 2,
            E_ABORT = 3
        }
        
        static public Int32 FileLen;
        static public String FileName;
        static public String Message;
        static public FileStream FileStream;
        static public int FilePtr;
        static public long PacketSize;
        static public ProgressType ProgressEvent;
        static public byte[] SendMsg = new byte[5];
        static public ACKType AckResult;
        static public bool Receive;
        static public byte[] DataPacket = new byte[132];
        static public string[] Files;
        static public int FileIndex;
        static public int ErrorCount;

        static public void Create(byte command, byte[] Data)
        {
            //byte[] crcBuff = new byte[4];
            byte[] crcBuff = new byte[2];
            //UInt32 rslt;

            //Globals.DataPacket = new byte[Data.Length + 6];
            Globals.DataPacket = new byte[Data.Length + 4];
            //byte[] buff = new byte[Globals.DataPacket.Length - 4];
            byte[] buff = new byte[Globals.DataPacket.Length - 2];
            Globals.DataPacket[0] = (byte)Globals.DataPacket.Length;
            Globals.DataPacket[1] = command;
            for (int i = 0; i < Data.Length; i++)
            {
                Globals.DataPacket[i + 2] = Data[i];
            }
            for (int i = 0; i < buff.Length; i++)
            {
                buff[i] = Globals.DataPacket[i];
            }
            Crc16 crc = new Crc16();
            //rslt = Crc32.Compute(buff);
            //crcBuff = BitConverter.GetBytes(rslt);
            crcBuff = crc.ComputeChecksumBytes(buff);
            ushort test = crc.ComputeChecksum(buff);
            //for (int i = 0; i < 4; i++)
            for (int i = 0; i < 2; i++)
            {
                if (BitConverter.IsLittleEndian)
                {
                    //Globals.DataPacket[Globals.DataPacket.Length - 4 + i] = crcBuff[3 - i];
                    Globals.DataPacket[Globals.DataPacket.Length - 2 + i] = crcBuff[1 - i];
                }
                else
                {
                    //Globals.DataPacket[Globals.DataPacket.Length - 4 + i] = crcBuff[i];
                    Globals.DataPacket[Globals.DataPacket.Length - 2 + i] = crcBuff[i];
                }
            }
        }
    }
}
